<template>
  <div>
    <el-tree
      style="max-width: 600px"
      :data="categoryTree"
      :props="defaultProps"
      :expand-on-click-node="false"
      node-key="catId"
      highlight-current
      @node-click="handleNodeClick"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <div>
            <el-button type="primary" link @click="add(data)">
              Add
            </el-button>
            <el-button
              style="margin-left: 4px"
              type="danger"
              link
              @click="remove(node, data)"
            >
              Remove
            </el-button>
          </div>
        </span>
      </template>
    </el-tree>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import baseService from "@/service/baseService";
import {ElMessage, ElMessageBox} from "element-plus";
import http from "@/utils/http";

const categoryTree = ref([])
const defaultProps = {
  children: 'children',
  label: 'name',
  value: 'catId'
}

const getTree = () => {
  baseService.get('/product/category/tree').then(res => {
    categoryTree.value = res.data
  })
}

const handleNodeClick = (data: any) => {
  // console.log('Selected node:', data)
}

const add = (data: any) => {
  console.log('Add node:', data)
}

const remove = (node: any, data: any) => {
  console.info("@>>> Remove Node: ", data)
  if (data.children && data.children.length > 0) {
    ElMessage({
      grouping: true,
      type: 'warning',
      duration: 3000,
      showClose: true,
      message: 'Please remove all children nodes first.',
      icon: 'info'
    })
    return
  }
  if (data.catId) {
    ElMessageBox.confirm("确定进行[删除]操作?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      http({
        url: '/product/category',
        data: [data.catId],
        method: "delete"
      }).then(resp => {
        ElMessage({
          grouping: true,
          type: 'success',
          duration: 3000,
          showClose: true,
          message: resp.msg,
          icon: 'info'
        })
        getTree()
      }).catch(err => {})
    })
  }
}

onMounted(() => {
  getTree()
})
</script>

<style scoped lang="less">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .product-count {
    color: #999;
    font-size: 12px;
  }
}
</style>
